//
//  KLMHomeController.swift
//  KLMHome
//
//  Created by Nic on 2025/2/17.
//

import UIKit

class KLMHomeController: KLMBaseController {
    
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var allDevicesBtn: KLMBaseButton!
    @IBOutlet weak var roomListBtn: KLMBaseButton!
    
    @IBOutlet weak var locationLabel: UILabel!
    @IBOutlet weak var tagIcon: UIImageView!
    @IBOutlet weak var weatherLabel: UILabel!
    @IBOutlet weak var temperatureLabel: UILabel!
    
    @IBOutlet weak var weekView1: KLMWeekDayView!
    @IBOutlet weak var weekView2: KLMWeekDayView!
    @IBOutlet weak var weekView3: KLMWeekDayView!
    
    @IBOutlet weak var placeImgView: UIImageView!
    
    weak var navLeftItem: KLMBaseButton?
    
    private var popView: YBPopupMenu?
    private var homeList: [KLMHomeParticipant] = [] {
        didSet {
            if homeList.count > 0 {
                popViewTitles = homeList.map({ $0.meshName })
                popViewTitles.append("家庭管理")
            }
        }
    }
    private var popViewTitles = [String]()
    private var popViewImages = [String]()
    private var currentHome: KLMHomeParticipant?
    private var currentHomeInfo: KLMHomeInfo?
    
    // MARK: - 家庭id变化
    private var currentHomeId: Int? = KLMUserDefault.getValue(for: .currentSelectedHomeId) as? Int {
        didSet {
            KLMUserDefault.setValue(for: .currentSelectedHomeId, with: currentHomeId)
            
            /// 刷新当前家庭的mesh配置
            queryHomeInfo(homeId: currentHomeId)
        }
    }
    // MARK: - 下标切换
    private var currentHomeIndex: Int? {
        didSet {
            if let index = currentHomeIndex, popViewTitles.count > 0, index < popViewTitles.count {
                popViewImages = Array(repeating: "", count: popViewTitles.count - 1)
                popViewImages.append("manage_home")
                popViewImages[index] = "home_check"
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let homeItem = KLMBaseButton(position: .imageTop(spacing: 0), image: "Nav_Current_Home")
        navLeftItem = homeItem
        navigationItem.leftBarButtonItem = UIBarButtonItem.itemWithBaseButton(homeItem, target: self, action: #selector(manageHome))
        view.backgroundColor = rgba(243, 243, 246, 1)
        /// 创建家庭通知
        NotificationCenter.default.addObserver(self, selector: #selector(createHomeRefresh(_:)), name: .createHomeSuccess, object: nil)
        /// 离开、删除家庭通知
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeRefresh(_:)), name: .deleteHomeSuccess, object: nil)
        /// 加入家庭
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeRefresh(_:)), name: .joinHomeSuccess, object: nil)
        /// 家庭名称改变
        NotificationCenter.default.addObserver(self, selector: #selector(loadHomeRefresh(_:)), name: .homeNameChanged, object: nil)
        
        refreshHomeList(homeId: self.currentHomeId)
    }
    // MARK: - 请求家庭列表
    func getHomeList(success: @escaping ([KLMHomeParticipant]) -> ()) {
        SVProgressHUD.show()
        KLMRequest.queryHomeList { response in
            SVProgressHUD.dismiss()
            if let homes = response as? [KLMHomeParticipant] {
                self.homeList = homes
                KLMHomeList.saveHomeList(list: homes)
                success(homes)
            }
        } failure: { error in
            KLMHttpShowError(error)
        }
    }
    
    // MARK: - 刷新家庭列表，并切换选择状态
    func refreshHomeList(homeId: Int?) {
        getHomeList { homes in
            self.selectHome(by: homeId, homes: homes)
        }
    }
    
    // MARK: - 选中某个家庭
    func selectHome(by homeId: Int?, homes: [KLMHomeParticipant]) {
        if homes.count > 0 {
            if let homeId = homeId, let index = homes.firstIndex(where: { $0.id == homeId
            }) {
                self.currentHome = homes[index]
                self.currentHomeIndex = index
                self.nameLabel.text = homes[index].meshName
                self.currentHomeId = homes[index].id
                self.switchPopViewSelectIndex(index: index)
                return
            }
            /// 当前家庭列表没有上次选中的房间ID，默认选中第一个
            self.currentHome = homes.first
            self.currentHomeId = homes.first?.id
            self.currentHomeIndex = 0
            self.nameLabel.text = homes.first?.meshName
            self.switchPopViewSelectIndex(index: 0)
            
        } else {
            self.currentHome = nil
            self.currentHomeId = nil
            self.nameLabel.text = "我的家..."
            KLMUserDefault.setValue(for: .currentSelectedHomeId, with: nil)
            self.popViewTitles.removeAll()
            self.popViewImages.removeAll()
        }
    }
    
    // MARK: - 请求家庭信息，获取mesh配置，同步到本地
    func queryHomeInfo(homeId: Int?) {
        print("请求家庭信息...")
        ///移除在线设备
        KLMHomeMesh.instacnce.onLineNodes.removeAll()
        
        guard let homeId = homeId else {
            KLMHomeMesh.removeHome()
            (UIApplication.shared.delegate as! AppDelegate).createNewMeshNetwork()
            return
        }
        
        KLMRequest.getHomeInfo(id: homeId) { response in
            if let homeInfo = response as? KLMHomeInfo {
                self.currentHomeInfo = homeInfo
                
                KLMHomeMesh.saveHome(home: homeInfo)
                KLMHomeMesh.loadHomeMeshDataAndReload(meshConfiguration: homeInfo.meshConfiguration)
            }
        } failure: { error in
            KLMHttpShowError(error)
        }
    }
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        containerView.isHidden = true
        placeImgView.contentMode = .scaleToFill
        placeImgView.image = UIImage(named: "Weather_no_data")?.stretchImage(hPadding: 10, vPadding: 10)
        
        nameLabel.configStyle(with: "我的家...", font: UIFont(safeName: "PingFang-SC-Bold", size: 18), titleColor: rgba(38, 38, 38, 1))
//        containerView.backgroundColor = .clear
//        containerView.layer.cornerRadius = 12
//        containerView.clipsToBounds = true
//        
//        tagIcon.image = UIImage(named: "weather_sun")
//        weatherLabel.text = "晴天"
//        temperatureLabel.text = "25 ºC"
//        
//        locationLabel.font = UIFont(safeName: "PingFangHK-Semibold", size: 18)
//        weatherLabel.font = UIFont(safeName: "Rubik-Medium", size: 12)
//        temperatureLabel.font = UIFont(safeName: "PingFangSC-Medium", size: 13)
//        
//        weekView1.refresh(day: "周一", icon: "weather_cloudy", temp: "22 ºC")
//        weekView2.refresh(day: "周二", icon: "weather_rainy", temp: "23 ºC")
//        weekView3.refresh(day: "周三", icon: "weather_sun", temp: "26 ºC")
        
        allDevicesBtn.setupContent(position: .imageLeading(spacing: 12), image: "All_devices", title: KLMLocalizable.LANGLOC("All devices"))
        allDevicesBtn.configStyle(font: UIFont(safeName:"PingFangSC-Regular", size: 16), titleColor: rgba(38, 38, 38, 1))
        roomListBtn.setupContent(position: .imageLeading(spacing: 12), image: "Room_list", title: KLMLocalizable.LANGLOC("Room List"))
        roomListBtn.configStyle(font: UIFont(safeName:"PingFangSC-Regular", size: 16), titleColor: rgba(38, 38, 38, 1))
    }
    
    override func applyTheme(_ theme: any Theme) {
        
//        locationLabel.textColor = theme.btnTextColor
//        weatherLabel.textColor = theme.btnTextColor
//        temperatureLabel.textColor = theme.btnTextColor
        
        let allImg = UIImage.image(withColor: .white, size: allDevicesBtn.bounds.size, cornerRadius: 8)
        allDevicesBtn.configStyle(bgImage: allImg)
        
        let roomImg = UIImage.image(withColor: .white, size: roomListBtn.bounds.size, cornerRadius: 8)
        roomListBtn.configStyle(bgImage: roomImg)
    }
    
    @objc func manageHome() {
        if homeList.count > 0 {
            showSelectHome()
        }
    }
    
    @objc func createHomeRefresh(_ notify: Notification) {
        refreshHomeList(homeId: notify.userInfo?[NotificationKey.createHomeKey] as? Int)
    }
    
    @objc func loadHomeRefresh(_ notify: Notification) {
        refreshHomeList(homeId: self.currentHomeId)
    }
    
    func showSelectHome() {
        let popViewMaxH = KLMScreenH - KLM_NavBarHeight - KLM_TabbarHeight
        if let popView = popView { ///弹过弹框
            popView.delegate = self
            popView.maxVisibleCount = min(popViewTitles.count, Int(popViewMaxH / popView.itemHeight))
            popView.show()
        } else { ///没弹过
            if popViewImages.count == 0 {
                var items = Array(repeating: "", count: popViewTitles.count - 1)
                items.append("manage_home")
                popViewImages = items
            }
            let padding = 16.0
            YBPopupMenu.showRely(on: navLeftItem, titles: popViewTitles, icons: popViewImages, menuWidth: view.width - 2*padding) {[weak self] popupMenu in
                guard let self = self else { return }
                popupMenu?.priorityDirection = .bottom
                popupMenu?.arrowHeight = 0
                popupMenu?.maxVisibleCount = min(popViewTitles.count, Int(popViewMaxH / (popupMenu?.itemHeight ?? 44.0)))
                popupMenu?.minSpace = padding
                popupMenu?.dismissOnSelected = false
                popupMenu?.isShadowShowing = false
                popupMenu?.delegate = self
                popupMenu?.cornerRadius = 8
                self.popView = popupMenu
            }
        }
    }
    @IBAction func tapAllDevices(_ sender: UIButton) {
        let allVc = KLMAllDevicesController(listType: .home, homeId: currentHomeId, homeRoom: nil)
        allVc.titleText = KLMLocalizable.LANGLOC("All devices")
        navigationController?.pushViewController(allVc, animated: true)
    }
    
    @IBAction func tapRoomList(_ sender: UIButton) {
        tabBarController?.selectedIndex = 1
    }
    
    /// 切换弹出家庭选择view的选择状态
    func switchPopViewSelectIndex(index: Int, updateTitles: Bool = true) {
        if let popView = popView, index < popView.titles.count, index < homeList.count {
            currentHomeIndex = index
            nameLabel.text = homeList[index].meshName
            currentHomeId = homeList[index].id
            
            print("当前切换选择的家庭名称是\(homeList[index].meshName)")
            if updateTitles {
                popView.setValue(popViewTitles, forKeyPath: "titles")
            }
            
            popView.setValue(popViewImages, forKeyPath: "images")
            popView.tableView.reloadSections(IndexSet(integer: 0), with: .fade)
        }
    }
}
extension KLMHomeController: YBPopupMenuDelegate {
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
        ybPopupMenu.tableView.deselectRow(at: IndexPath(row: index, section: 0), animated: false)
        if index == ybPopupMenu.titles.count - 1 {
            ybPopupMenu.dismiss()
            /// 跳转到家庭管理
            let vc = KLMHomeManageController()
            navigationController?.pushViewController(vc, animated: true)
        } else {
//            if index < homeList.count {
//                KLMUserDefault.setValue(for: .currentSelectedHomeId, with: homeList[index].id)
//            }
            switchPopViewSelectIndex(index: index, updateTitles: false)
            // 延迟 2 秒后执行代码
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                ybPopupMenu.dismiss()
            }
        }
    }
    
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, cellForRowAt index: Int) -> UITableViewCell! {
        
        let cellId = "HomeCellId"
        var cell = ybPopupMenu.tableView.dequeueReusableCell(withIdentifier: cellId)
        if (cell == nil) {
            cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: cellId)
            cell?.textLabel?.numberOfLines = 0
        }
        cell?.textLabel?.text = ybPopupMenu.titles[index] as? String
        cell?.backgroundColor = .clear
        cell?.imageView?.image = UIImage.image(withColor: .clear, size: CGSize(width: 24, height: 24))
        if let image = ybPopupMenu.images[index] as? String, let img = UIImage(named: image) {
            cell?.imageView?.image = img
        }
        return cell
    }
}
